package cn.com.yusys.yusp.admin.service;

import cn.com.yusys.yusp.admin.Utils.IDUtils;
import cn.com.yusys.yusp.admin.repository.mapper.VillageInformationMapper;
import cn.com.yusys.yusp.commons.mapper.QueryModel;
import cn.com.yusys.yusp.commons.web.rest.dto.ResultDto;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class VillageInformationService {

    @Value("${Doc.uploadPath}")
    private String UP_ROOT_PATH;

    @Value("${Doc.filePath}")
    private String FILE_PATH;

    @Resource
    VillageInformationMapper villageInformationMapper;

    @Transactional
    public Integer addVillage(QueryModel model) {
        return villageInformationMapper.addVillage(model);
    }

    //excel导入
    @Transactional
    public int excelAddNewCustomer(List<QueryModel> list) {
        return villageInformationMapper.excelAddNewCustomer(list);
    }
    
    @Transactional
    public Integer updateCustomerImport(QueryModel model) {
        return villageInformationMapper.updateCustomerImport(model);
    }

    @Transactional
    public Integer updateVillageInformation(QueryModel model) {
        return villageInformationMapper.updateVillageInformation(model);
    }


    @Transactional
    public Integer updateOtherIndustry(QueryModel model) {
        return villageInformationMapper.updateOtherIndustry(model);
    }

    @Transactional
    public Integer updateGridPersonnel(QueryModel model) {
        return villageInformationMapper.updateGridPersonnel(model);
    }

    @Transactional
    public Integer addVillageDetail(QueryModel model) {
        //通过传入的id删除表中的图片
//        Integer state =  villageInformationMapper.deleteVillageImageById(model);
        //删除完成后再插入进表
            List imageList = (List) model.getCondition().get("fileList");
            String uuid= UUID.randomUUID().toString().replaceAll("-", "");
            for (int i =0;i<imageList.size();i++){
                //此处需要改善
                Map map = new HashMap();
                map.put("custId",uuid);
                map.put("fileList",FILE_PATH + "/" + imageList.get(i));
                villageInformationMapper.addVillageImage(map);
        }
        model.getCondition().put("custId", uuid);
        return villageInformationMapper.addVillageDetail(model);
    }


    @Transactional
    public Integer addOtherIndustryDetail(QueryModel model) {
        //通过传入的id删除表中的图片
//        Integer state =  villageInformationMapper.deleteOtherIndustryImageById(model);
        //删除完成后再插入进表
        List imageList = (List) model.getCondition().get("fileList");
        String uuid= UUID.randomUUID().toString().replaceAll("-", "");
        for (int i =0;i<imageList.size();i++){
            //此处需要改善
            Map map = new HashMap();
            map.put("custId",uuid);
            map.put("fileList",FILE_PATH + "/" + imageList.get(i));
            villageInformationMapper.addVillageImage(map);
        }
        model.getCondition().put("custId", uuid);
        return villageInformationMapper.addOtherIndustryDetail(model);
    }

    //根据用户的归属进行显示：查询条件为用户的id，根据id去统计出显示的内容
    @Transactional(readOnly = true)
    public List<Map<String, Object>> getAllVillageInformation(QueryModel model) {
        PageHelper.startPage(model.getPage(), model.getSize());
        List<Map<String, Object>> list = villageInformationMapper.getAllVillageInformation(model);
        PageHelper.clearPage();
        return list;
    }

    //查询对应村的其他行业信息
    @Transactional(readOnly = true)
    public List<Map<String, Object>> getOtherIndustry(QueryModel model) {
        PageHelper.startPage(model.getPage(), model.getSize());
        List<Map<String, Object>> list = villageInformationMapper.getOtherIndustry(model);
        PageHelper.clearPage();
        return list;
    }

    //查询对应村的其他行业信息
    @Transactional(readOnly = true)
    public List<Map<String, Object>> getVillageCustList(QueryModel model) {
        PageHelper.startPage(model.getPage(), model.getSize());
        List<Map<String, Object>> list = villageInformationMapper.getVillageCustList(model);
        PageHelper.clearPage();
        return list;
    }

    //查询对应村的其他行业信息
    @Transactional(readOnly = true)
    public List<Map<String, Object>> getOtherIndustryCustList(QueryModel model) {
        PageHelper.startPage(model.getPage(), model.getSize());
        List<Map<String, Object>> list = villageInformationMapper.getOtherIndustryCustList(model);
        PageHelper.clearPage();
        return list;
    }

    //新增其他行业信息
    @Transactional
    public Integer addOtherIndustry(QueryModel model) {
        return villageInformationMapper.addOtherIndustry(model);
    }

    @Transactional
    public int deleteOtherIndustry(List<Integer> list) {
        return villageInformationMapper.deleteOtherIndustry(list);
    }



    //删除选定的其他行业

    //更新其他行业信息

    @Transactional(readOnly = true)
    public List<Map<String, Object>> getGridName(QueryModel model) {
        return villageInformationMapper.getGridName(model);
    }

    @Transactional(readOnly = true)
    public List<Map<String, Object>> getOrgName(QueryModel model) {
        return villageInformationMapper.getOrgName(model);
    }

    @Transactional(readOnly = true)
    public List<Map<String, Object>> getOtherIndustryName(QueryModel model) {
        return villageInformationMapper.getOtherIndustryName(model);
    }

    @Transactional(readOnly = true)
    public List<Map<String, Object>> getCustomerManagerVillageInformation(QueryModel model) {
        PageHelper.startPage(model.getPage(), model.getSize());
        List<Map<String, Object>> list = villageInformationMapper.getCustomerManagerVillageInformation(model);
        PageHelper.clearPage();
        return list;
    }

    @Transactional(readOnly = true)
    public List<Map<String, Object>> getSubBranchManagerVillageInformation(QueryModel model) {
        PageHelper.startPage(model.getPage(), model.getSize());
        List<Map<String, Object>> list = villageInformationMapper.getSubBranchManagerVillageInformation(model);
        PageHelper.clearPage();
        return list;
    }

    @Transactional(readOnly = true)
    public List<Map<String, Object>> getBranchManagerVillageInformation(QueryModel model) {
        PageHelper.startPage(model.getPage(), model.getSize());
        List<Map<String, Object>> list = villageInformationMapper.getBranchManagerVillageInformation(model);
        PageHelper.clearPage();
        return list;
    }

    @Transactional(readOnly = true)
    public Map<String, Object> getVillageInformation(QueryModel model) {
        return villageInformationMapper.getVillageInformation(model);
    }

    @Transactional(readOnly = true)
    public Map<String, Object> getVillageIndustryInformation(QueryModel model) {
        return villageInformationMapper.getVillageIndustryInformation(model);
    }

    @Transactional(readOnly = true)
    public Map<String, Object> getGridPersonnel(QueryModel model) {
        return villageInformationMapper.getGridPersonnel(model);
    }

    /**
     * 上传附件业务逻辑
     *
     * @param uploadFile
     */
    public String fileUpload(MultipartFile uploadFile) {
        try {
            InputStream in = uploadFile.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            // 文件上传的路径
            String path =
                    UP_ROOT_PATH
                            + "/"
                            + uploadFile.getOriginalFilename();

            File file = new File(path);
            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            OutputStream out = new FileOutputStream(path);
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.close();
            in.close();
            return FILE_PATH + "/" +uploadFile.getOriginalFilename();
        } catch (IOException e) {
            return "系统错误，请联系管理员";
        }
    }

    @Transactional(readOnly = true)
    public Map<String, Object> getVillageDetail(QueryModel model) {
        List<Map<String, Object>> list = null;
        list = villageInformationMapper.getVillageCustDetailImage(model);
        for(int i=0;i<list.size();i++){
            String str = (String) list.get(i).get("fileList");
            if (!str.equals("")){
                String fileName=str.substring(((String) list.get(i).get("fileList")).lastIndexOf("/")+1);
                list.get(i).put("name",fileName);
                list.get(i).put("url",list.get(i).get("fileList"));
            }
        }
        Map<String, Object>  map = villageInformationMapper.getVillageDetail(model);
        map.put("fileList",list);
        return map;
    }

    @Transactional(readOnly = true)
    public Map<String, Object> getOtherIndustryDetail(QueryModel model) {
        List<Map<String, Object>> list = null;
        list = villageInformationMapper.getOtherIndustryCustDetailImage(model);
        for(int i=0;i<list.size();i++){
            String str = (String) list.get(i).get("fileList");
            if (!str.equals("")){
                String fileName=str.substring(((String) list.get(i).get("fileList")).lastIndexOf("/")+1);
                list.get(i).put("name",fileName);
                list.get(i).put("url",list.get(i).get("fileList"));
            }
        }
        Map<String, Object>  map = villageInformationMapper.getOtherIndustryCustDetail(model);
        map.put("fileList",list);
        return map;
    }

    @Transactional(readOnly = true)
    public Map<String, Object> getVillageCustDetailImage(QueryModel model) {
        List<Map<String, Object>> list = null;
        list = villageInformationMapper.getVillageCustDetailImage(model);
        for(int i=0;i<list.size();i++){
            String str = (String) list.get(i).get("fileList");
            if (!str.equals("")){
                list.get(i).put("url",list.get(i).get("fileList"));
            }
        }
//        Map<String, Object>  map = villageInformationMapper.getVillageCustDetail(model);
        Map<String, Object>  map = new HashMap<>();
        map.put("fileList",list);
        return map;
    }

    @Transactional(readOnly = true)
    public Map<String, Object> getOtherIndustryCustDetailImage(QueryModel model) {
        List<Map<String, Object>> list = null;
        list = villageInformationMapper.getOtherIndustryCustDetailImage(model);
        for(int i=0;i<list.size();i++){
            String str = (String) list.get(i).get("fileList");
            if (!str.equals("")){
                list.get(i).put("url",list.get(i).get("fileList"));
            }
        }
//        Map<String, Object>  map = villageInformationMapper.getOtherIndustryCustDetail(model);
        Map<String, Object>  map = new HashMap<>();
        map.put("fileList",list);
        return map;
    }

    /**
     * 通过身份证去查询客户表中是否存在
     * 通过身份证信息去查询审批信息表中的审批状态为0或1的也不能通过
     * 都验证通过就插入进表中
     */
    @Transactional
    public ResultDto<Object> transferCustomer(QueryModel model) {
        ResultDto<Object> resultDto = new ResultDto<>();
        Map<String,Object> isExistCustomer = villageInformationMapper.isExistCustomer(model);
        if (isExistCustomer ==null){
            resultDto.setCode(100);
            resultDto.setMessage("客户不存在，请先创建客户");
            return resultDto;
        }
        String appStatus = villageInformationMapper.selectAppStatus(model);
        if (appStatus != null){
            if (appStatus.equals("0")){
                resultDto.setCode(200);
                resultDto.setMessage("该客户已在审批中");
                return resultDto;
            }else if (appStatus.equals("1")){
                resultDto.setCode(250);
                resultDto.setMessage("该客户已经审批过了");
                return resultDto;
            }
        }
        model.getCondition().put("id", IDUtils.getGuid());
        model.getCondition().put("custNo",isExistCustomer.get("custNo"));
        model.getCondition().put("custName",isExistCustomer.get("custName"));
        int insertUserTransfer = villageInformationMapper.insertUserTransfer(model);
        model.getCondition().put("approverNo","1368");
        model.getCondition().put("approverName","庄文达");
        model.getCondition().put("approvalType","2");
        int insertProcessNode = villageInformationMapper.insertProcessNode(model);
        if (insertUserTransfer == 1 && insertProcessNode == 1){
            resultDto.setCode(300);
            resultDto.setMessage("用户移交已发送");
        }
        return resultDto;
    }

    public List<String> selectExistCustInfo(List<String> list){
        return villageInformationMapper.selectExistCustInfo(list);
    }
}
